<?php

require_once 'common/conn.php';
require_once 'common/common.php';

$action = getParameter("action");
if ($action == "getFriendByUsercode") {
    $usercode = getParameter("usercode");
    if ($usercode != "") {
        $db = new DBC();
        $sql = "SELECT devicecode AS usercode,nickname,sex,headID FROM t_device WHERE devicecode IN(SELECT friendCode FROM t_a_friend WHERE usercode = '" . $usercode . "')";
        $data = $db->fetchData($sql);
        for ($i = 0; $i < count($data); $i++) {
            if (isNull($data[$i]['headID'])) {
                $data[$i]['headID'] = "BBAA000";
            }
        }
    } else {
        $data = array();
    }
    echo json_encode($data);
} else if ($action == "add") {
    $resultArray = array();
    $usercode = getParameter("usercode");
    $nickname = getParameter("nickname");
    if ($usercode != "" && $nickname != "") {
        $db = new DBC();
        $sql = "SELECT devicecode AS friendCode FROM t_device WHERE nickname = '" . $nickname . "'";
        $data = $db->fetchData($sql);
        if (checkArrayNotEmpty($data)) {
            $sql = "INSERT INTO t_a_friend(usercode,friendCode,createTime) VALUES('" . $usercode . "','" . $data[0]['friendCode'] . "',now())";
            $db->execute($sql);
            $sql = "INSERT INTO t_a_friend(usercode,friendCode,createTime) VALUES('" . $data[0]['friendCode'] . "','" . $usercode . "',now())";
            $db->execute($sql);
            $resultArray['errorNo'] = "0";
            $resultArray['errorMsg'] = "";
        } else {
            $resultArray['errorNo'] = "3";
            $resultArray['errorMsg'] = "昵称为 " . $nickname . " 的用户不存在。";
        }
    } else {
        $resultArray['errorNo'] = "2";
        $resultArray['errorMsg'] = "参数不完整";
    }
//    echo json_encode(true);
    echo json_encode($resultArray);
} else if (($action == "delete")) {
    $usercode = getParameter("usercode");
    $nickname = getParameter("nickname");
    if ($usercode != "" && $nickname != "") {
        $db = new DBC();
        $sql = "SELECT devicecode AS friendCode FROM t_device WHERE nickname = '" . $nickname . "'";
        $data = $db->fetchData($sql);
        if (checkArrayNotEmpty($data)) {
            $sql = "DELETE FROM t_a_friend WHERE usercode = '" . $usercode . "' AND friendCode = '" . $data[0]['friendCode'] . "'";
            $db->execute($sql);
            $sql = "DELETE FROM t_a_friend WHERE friendCode = '" . $usercode . "' AND usercode = '" . $data[0]['friendCode'] . "'";
            $db->execute($sql);
        }
    }
    echo json_encode(true);
}
?>
